package com.qk.mangement.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.aliyun.oss.model.OSSObjectSummary;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qk.common.util.AliYunOSSOperators;
import com.qk.entity.User;
import com.qk.mangement.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Date:2025/10/13
 * Author:zxc
 * Description
 */
@Component
@Slf4j
public class AliYunOssTask {

    @Autowired
    private AliYunOSSOperators aliYunOSSOperators;
    @Autowired
    private UserMapper userMapper;
    @Scheduled(cron = "0 0 1  * * * ")
    public void cleanRedundantFiles() throws Exception {
        log.info("定时任务开始清理多余文件");
        log.info("当前时间：{}", LocalDateTime.now());
        String today = LocalDateTimeUtil.format(LocalDateTime.now(), "yyyy/MM/dd");
        List<String> allImages = aliYunOSSOperators.listFiles(today).stream().map(OSSObjectSummary::getKey).collect(Collectors.toList());
        String newToday = today.replace("/", "-");
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(User::getCreateTime, newToday);
        List<String> userImages = userMapper.selectList(queryWrapper).stream()
                .map(user -> {
                    int index = user.getImage().indexOf("com/");
                    return user.getImage().substring(index + 4);
                }).collect(Collectors.toList());
        List<String> deleteImages = new ArrayList<>();
        for (String allImage : allImages) {
            if (!userImages.contains(allImage)) {
                deleteImages.add(allImage);
            }
        }
        log.info("待删除文件：{}", deleteImages);
        if (CollectionUtil.isNotEmpty(deleteImages)){
            aliYunOSSOperators.batchDeleteFiles(deleteImages);
        }
    }
}
